/*
 *  Copyright (C) 2004 Cidero, Inc.
 *
 *  Permission is hereby granted to any person obtaining a copy of 
 *  this software to use, copy, modify, merge, publish, and distribute
 *  the software for any non-commercial purpose, subject to the
 *  following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY IN CONNECTION WITH THE SOFTWARE.
 * 
 *  File: $RCSfile: URLUtil.java,v $
 *
 */
package com.cidero.util;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.net.URLDecoder;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.regex.*;

/**
 * URL utility method class.  A few handy extras...
 */
public class URLUtil
{
  private static Logger logger = Logger.getLogger("com.cidero.util");

  /** 
   * Return the tail of the URL path, trimming off any extension
   */
  public static String getPathTail( String url )
  {
    // Try and make a title out of the end of the resource path
    int index = url.lastIndexOf("/");

    // Make sure we're past the 2nd slash in the http://
    if( index > 8 )
    {
      String title = trimFileExtension( url.substring( index+1 ) );
      title = URLDecoder.decode(title);
      return title;
    }
    return null;
  }

  /**
   *  Trim a file extension off a filename
   */
  public static String trimFileExtension( String filename )
  {
    int index = filename.lastIndexOf(".");
    if( index < 0 )
      return filename;
    else
      return filename.substring(0, index);
  }

  /**
   *  Get a simple 'proxified' version of a URL. Example:
   *
   *  http://64.236.34.196:80/stream/2001    
   *
   *    gets changed to:
   * 
   *  http://<proxyHost>:<proxyPort>/64.236.34.196:80/stream/2001
   *
   *  or, if optArg is non-null
   *
   *  http://<proxyHost>:<proxyPort>/opt:name1=val1,name2=val2/64.236.34.196:80/stream/2001
   *
   *  @param optarg  Optional arg
   */
  public static String urlToProxy( String url,
                                   String proxyHost, int proxyPort,
                                   String optarg )
  {
    String tmp;
    if( optarg == null )
    {
      tmp = url.replaceFirst("[/][/]",
                             "//" + proxyHost + ":" + proxyPort + "/" );
    }
    else
    {
      tmp = url.replaceFirst("[/][/]",
                             "//" + proxyHost + ":" + proxyPort +
                             "/" + optarg + "/" );
    }
    
    logger.finest("Outgoing proxy URL for '" + url + "' is: '" + tmp + "'" );

    return tmp;
  }

  public static String proxyToURL( String proxyURL )
  {
    String tmp = proxyURL.replaceFirst("[/][/][^/]*", "/" );
    return tmp;
  }


  public static String replaceHostAddr( String url,
                                        String newAddr )
  {
    String tmp = url.replaceFirst("[/][/][^/:]*", "//" + newAddr );
    return tmp;
  }

  /**
   *  Return host portion of URL. This function exists to conveniently 
   *  handle non-standard protocols (different than 'http','file','ftp',
   *  such as 'mms', 'rhap', 'rtsp', etc...). The URL class throws 
   *  exceptions for non-standard protocols unless special protocol handlers 
   *  are installed
   */  
  public static String getHost( String url )
  {
    Pattern patt = Pattern.compile( "[/][/]([^/:]*)", Pattern.DOTALL );
    Matcher matcher = patt.matcher( url );
    
    if( matcher.find() )
    {
      return matcher.group(1);  // Don't include leading double-slash
    }
    else
    {
      logger.warning("No host found in URL '" + url + "'" );
      return null;
    }
  }
  
  public static void main( String args[] )
  {
    String url = "http://64.236.34.196:80/stream/2001";
    String urlProxy = urlToProxy( url, "192.168.1.12", 18080, null );
    String urlOrig = proxyToURL( urlProxy );

    System.out.println("Starting URL: " + url );
    System.out.println("Proxy URL: " + urlProxy );
    System.out.println("Original URL: " + urlOrig );

    url = "http://64.236.34.196/stream/2001";
    urlProxy = urlToProxy( url, "192.168.1.12", 18080, null );
    urlOrig = proxyToURL( urlProxy );

    System.out.println("\nStarting URL: " + url );
    System.out.println("Proxy URL: " + urlProxy );
    System.out.println("Original URL: " + urlOrig );

    url = "http://www.radioparadise.com:8089/stream/2001";
    urlProxy = urlToProxy( url, "192.168.1.12", 18080, null );
    urlOrig = proxyToURL( urlProxy );

    System.out.println("\nStarting URL: " + url );
    System.out.println("Proxy URL: " + urlProxy );
    System.out.println("Original URL: " + urlOrig );

    String urlOrigHost = "http://64.236.34.196:80/stream/2001";
    String urlReplacedHost = replaceHostAddr( urlOrigHost, "192.1.1.100" );
    
    System.out.println("Original Host URL: " + urlOrigHost );
    System.out.println("Replaced Host Addr: " + urlReplacedHost );

    String rhapsodyURL = "rhap://127.0.0.1:8080/stream/2001";

    System.out.println("Rhapsody URL host = " + URLUtil.getHost(rhapsodyURL));

    // Search for the interface addr on the host that is on the
    // same subnet as the renderer device
    String subnetHostAddr = 
      NetUtil.findInterfaceAddrOnSameSubnetAs( "192.168.1.1" );

    rhapsodyURL = URLUtil.replaceHostAddr( rhapsodyURL, subnetHostAddr );
    System.out.println("Fixed Rhapsody URL = " + rhapsodyURL );

    String trackMetaData = "<res size=\"12345\" http://url</res>";
    trackMetaData = trackMetaData.replaceAll(" size=\"[0-9]*\" http://", "><http://" );
    System.out.println("Fixed trackMetaData = " + trackMetaData );
    


  }

}

